from os import path
from rest_framework import serializers
from .models import AlloyPhaseDiagram

# 文件上传根目录
MEDIA_ROOT = 'C:/mat_gene_attachments/'


class AlloyPhaseDiagramSerializer(serializers.HyperlinkedModelSerializer):
    """
    合金相图序列化器
    """
    alloy_phase_diagram_filename = serializers.SerializerMethodField()

    class Meta:
        model = AlloyPhaseDiagram
        fields = ('url', 'alloy_name', 'alloy_code', 'alloy_phase_diagram','alloy_phase_diagram_filename')

    def get_alloy_phase_diagram_filename(self, obj):
        # 若没有附件，则返回''，否则返回文件名
        filename = obj.alloy_phase_diagram.name
        return '' if filename is None else path.basename(filename)